import React, { Component, Fragment } from 'react';
import { Link } from 'dva/router';
import { connect } from 'dva';
import router from 'umi/router';
import styles from './index.less';
import { Card, Switch, Input, Radio, Checkbox, Form, Button, message, Spin, Row, Col,Select, Tag,Icon,Modal,Cascader } from 'antd';
import regions from './regionData';
import {   
    generateTreeDataMap,
  } from '../delivery/tools';
import sameCityDelivery from '@/models/order/sameCityDelivery';

const RadioGroup = Radio.Group;
const FormItem = Form.Item;
let regionData=transformData(regions);
let regionDatas=[];
function transformData(data){
    let datas=data||[];
    datas.forEach((item,index)=>{
        item.value=item.Id;
        item.label=item.Name;
        item.children=item.Child;
        if(item.Child){
            transformData(item.Child)
        }
    })
    return datas;
}

@connect(({ sameCityDelivery, loading }) => ({
  sameCityAddress:sameCityDelivery.sameCityAddress
}))

@Form.create()
export default class Index extends Component {
    state={
        visible:false,
        searchLoading:false,
        hideSearchBox:true,
        areaErorr:false
    }

    componentWillMount(){
        window.Isoption = false;
        this.dataMap = generateTreeDataMap(regions, {}, -1);
        this.citycode="";
        //console.log(this.dataMap)
        let arr =[];
        regionData.forEach(item=>{
        if(item.children){
            item.children.forEach(v=>{
            arr.push(v)
            })
        }
        })
        regionDatas=regionData;  
    }

    componentDidMount(){
        window.Isoption = true;
        const {onRef} = this.props;
        onRef&&onRef(this);              
    }

    hideModal = () => {
        this.setState({
            visible:false,
            hideSearchBox:true,            
        },()=>{
            this.map.destroy();
        })
    }

    getIdByAreaCode = (id) => {
        let arr=[];
        // arr.push(this.dataMap[this.dataMap[this.dataMap[this.dataMap[id].Pid].Pid].Pid].Id)
        console.log(this.dataMap[this.dataMap[id].Pid].Pid,9900)
        if(this.dataMap[this.dataMap[id].Pid].Pid>6){
            let provinceId=this.dataMap[this.dataMap[this.dataMap[id].Pid].Pid].Id;
            if(provinceId<6){
                arr.push(this.dataMap[this.dataMap[id].Pid].Id)
                arr.push(this.dataMap[id].Id)
            }else{
                arr.push(provinceId)
                arr.push(this.dataMap[this.dataMap[id].Pid].Id)
                arr.push(this.dataMap[id].Id)
            }
        }else{
            arr.push(this.dataMap[this.dataMap[id].Pid].Id)
            arr.push(this.dataMap[id].Id)
        }
        
        return arr;
    }

    settingArea = (data) => {
        console.log(data,22)
        let that=this;
        let areaCode= this.getIdByAreaCode(data[0].adcode);
        this.citycode=data[0].adcode;
        console.log(areaCode)                                                                          
        let address=data[0].address;   
        let addressText=data[0].addressText;                         
        this.props.form.setFieldsValue({
            Region:areaCode,
            RegionText:addressText||address
        })  
        this.cityInfo={lng:data[0].location.lng,lat:data[0].location.lat};        
        // this.map.clearMap();
        // var marker = new AMap.Marker({
        //     map: this.map,
        //     position: [data[0].location.lng, data[0].location.lat],           
        // });
         //实例化信息窗体
        //var title = `<span>地址：</span>${address}`,
        var title = `<span>地址：</span>${address}`,
        content = [];                       
    // content.push("<a >设为联系地址</a>");
        var infoWindow = new AMap.InfoWindow({
            isCustom: true,  //使用自定义窗体
            content: that.createInfoWindow(that.map,title, content.join("<br/>"),1),
            offset: new AMap.Pixel(16, -5)
        });

        // infoWindow.open(that.map, marker.getPosition()); 
        infoWindow.open(that.map, data[0].location); 
        // that.setState({
        //     hideSearchBox:true
        // })
    }

    createInfoWindow = (map,title, content,type=2,data) => {
        let that=this;
        var info = document.createElement("div");        
       info.className = "custom-info input-card content-window-card"; 
       info.style.width= "260px";     
        //可以通过下面的方式修改自定义窗体的宽高   
        // 定义顶部标题
        var top = document.createElement("div");
        var titleD = document.createElement("div");
        var closeX = document.createElement("img");
        closeX.style.position='absolute';
        closeX.style.top='8px';
        closeX.style.right='8px';
        top.className = "info-top";
        top.style.backgroundColor='white';    
        titleD.innerHTML = title;
        titleD.style.lineHeight=1.4;
        closeX.src = "https://webapi.amap.com/images/close2.gif";
        closeX.onclick = function(){
            map.clearInfoWindow();
        };
    
        top.appendChild(titleD);
        top.appendChild(closeX);
       
    
        // 定义中部内容
        var middle = document.createElement("div");
        var a = document.createElement("a");
        middle.className = "info-middle";
        middle.style.backgroundColor = 'white';
        //middle.innerHTML = content;
        if(type==2&&this.cityInfo.lng !=data[0].location.lng&&this.cityInfo.lat!=data[0].location.lat){
            a.innerHTML="设为联系地址";
            a.onclick=function(){
                that.settingArea(data)
            }   
            middle.appendChild(a);     
        }
        info.appendChild(middle);
    
        //
        var box = document.createElement("div");
        box.style.padding="8px";
        box.style.paddingRight="16px";
        box.style.background= "#fff";
        info.style.boxSizing= "#border-box";
        box.style.border= "1px solid #ccc";
        box.appendChild(top);
        box.appendChild(middle);
        info.appendChild(box);
        // 定义底部内容
        var bottom = document.createElement("div");
        bottom.className = "info-bottom";
        bottom.style.position = 'relative';
        bottom.style.top = '-3px';
        bottom.style.margin = '0 auto';
        bottom.style.width = '30px';
        var sharp = document.createElement("img");
        sharp.src = "https://webapi.amap.com/images/sharp.png";
        bottom.appendChild(sharp);
        info.appendChild(bottom);
        return info;
    }

    showModal = () => {
        let that=this;
        this.setState({
            visible:true
        },()=>{
            setTimeout(()=>{
                this.map = new AMap.Map('distributionModalMapContainer', {                    
                   // center:[116.46,39.92],
                    zoom:13
                }); 
                 var scale = new AMap.Scale({
                    visible: true
                });
                var toolBar = new AMap.ToolBar({
                    visible: true
                });
                this.map.addControl(scale);
                this.map.addControl(toolBar);
                this.map.on('click', function(e){
                    var text = '您在 [ '+e.lnglat.getLng()+','+e.lnglat.getLat()+' ] 的位置单击了地图！';
                    console.log(e,text)
                    // that.setState({
                    //     hideSearchBox:true
                    // })
                   // that.map.clearMap();
                    var marker = new AMap.Marker({
                        map: that.map,
                        position: [e.lnglat.getLng(), e.lnglat.getLat()],
                        // icon: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b' + (i + 1) + '.png',
                        // extData: {
                        //     id: i + 1
                        // }
                    });
                    AMap.service('AMap.Geocoder',function(){//回调函数
                        //实例化Geocoder
                        var geocoder = new AMap.Geocoder({
                            city: ""//城市，默认：“全国”
                        });
                        var lnglatXY=[e.lnglat.getLng(),e.lnglat.getLat()];//地图上所标点的坐标
                        geocoder.getAddress(lnglatXY, function(status, result) {
                            if (status === 'complete' && result.info === 'OK') {
                                //获得了有效的地址信息:
                                //即，result.regeocode.formattedAddress
                                //console.log(result);
                               // var city = result.regeocode.addressComponent.city; 
                               that.setState({
                                   areaInfo:result.regeocode
                               })
                               let areaCode= that.getIdByAreaCode(result.regeocode.addressComponent.adcode);
                            //    that.citycode=result.regeocode.addressComponent.adcode;
                            //    console.log(areaCode,555)                                                                          
                            //    let address=result.regeocode.formattedAddress;                          
                            //    that.props.form.setFieldsValue({
                            //        Region:areaCode,
                            //        RegionText:`${result.regeocode.addressComponent.township}${result.regeocode.addressComponent.street}${result.regeocode.addressComponent.streetNumber}`
                            //    })                            
                               //实例化信息窗体
                                //var title = `<span>地址：</span>${address}`,
                                let areaText=`${result.regeocode.addressComponent.province}${result.regeocode.addressComponent.city}${result.regeocode.addressComponent.district}${result.regeocode.addressComponent.township}${result.regeocode.addressComponent.street}${result.regeocode.addressComponent.streetNumber}`;
                                let title = `<span>地址：</span>${areaText}`;
                                let regionText= `${result.regeocode.addressComponent.township}${result.regeocode.addressComponent.street}${result.regeocode.addressComponent.streetNumber}`;
                                let content = [];   
                                let arr=[{
                                    location:e.lnglat,
                                    address:areaText,
                                    addressText:regionText,
                                    adcode:result.regeocode.addressComponent.adcode
                                }];                    
                            // content.push("<a >设为联系地址</a>");
                                var infoWindow = new AMap.InfoWindow({
                                    isCustom: true,  //使用自定义窗体
                                    content: that.createInfoWindow(that.map,title, content.join("<br/>"),2,arr),
                                    offset: new AMap.Pixel(16, -5)
                                });

                                infoWindow.open(that.map, marker.getPosition());    
                            }                           
                            console.log(result,999);
                        });
                    })
                    marker.on('click', function(){
                        console.log('marker',this)                                                              
                        console.log(that.map,AMap.Geocoder,AMap.Text([this.getPosition().lng,this.getPosition().lat]))                        
                        let _this=this;
                        AMap.service('AMap.Geocoder',function(){//回调函数
                            //实例化Geocoder
                            var geocoder = new AMap.Geocoder({
                                city: ""//城市，默认：“全国”
                            });
                            var lnglatXY=[_this.getPosition().lng,_this.getPosition().lat];//地图上所标点的坐标
                            geocoder.getAddress(lnglatXY, function(status, result) {
                                if (status === 'complete' && result.info === 'OK') {
                                    //获得了有效的地址信息:
                                    //即，result.regeocode.formattedAddress
                                    //console.log(result);
                                   // var city = result.regeocode.addressComponent.city;
                                //    that.props.form.setFieldsValue({
                                //     RegionText:`${result.regeocode.addressComponent.township}${result.regeocode.addressComponent.neighborhood}`
                                //    })
                                   let regionText= `${result.regeocode.addressComponent.township}${result.regeocode.addressComponent.street}${result.regeocode.addressComponent.streetNumber}`;
                                   let address=result.regeocode.formattedAddress;
                                   let arr=[{
                                        location:e.lnglat,
                                        address:address,
                                        addressText:regionText,
                                        adcode:result.regeocode.addressComponent.adcode
                                    }];  
                                   //实例化信息窗体
                                    var title = `<span>地址：</span>${address}`,
                                    content = [];                       
                                // content.push("<a >设为联系地址</a>");
                                    var infoWindow = new AMap.InfoWindow({
                                        isCustom: true,  //使用自定义窗体
                                        content: that.createInfoWindow(that.map,title, content.join("<br/>"),2,arr),
                                        offset: new AMap.Pixel(16, -5)
                                    });

                                    infoWindow.open(that.map, _this.getPosition());    
                                }else{
                                   // var city = '获取失败';
                                    //获取地址失败
                                }
                                //document.getElementById("city").value=city;
                                console.log(result,999);
                            });
                        })
                    });
                });                
                this.getIntraCityAddress()
            },300)
            this.forceUpdate()
        })
    }

    getIntraCityAddress = () => {
        const {dispatch,form} = this.props;
        dispatch({
            type:"sameCityDelivery/GetIntraCityAddress",
            callback:{
                success:(data)=>{
                    //console.log(data)
                    if(data.Code==0&&data.Data&&data.Data.Lng){
                        form.setFieldsValue({
                            Region:[data.Data.ProvId,data.Data.CityId,data.Data.DistrictId],
                            RegionText:data.Data.Address
                        })
                        this.cityInfo={lng:data.Data.Lng,lat:data.Data.Lat};
                        let marker = new AMap.Marker({
                            position: [data.Data.Lng,data.Data.Lat],
                            //icon: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b' + (i + 1) + '.png',
                            // extData: {
                            //     id: i + 1
                            // },
                            map: this.map
                        });
                        let address=`${data.Data.Prov}${data.Data.City}${data.Data.District}${data.Data.Address}`;
                        this.map.setFitView([marker]);
                        var title = `<span>地址：</span>${address}`,
                        content = [];                                              
                        var infoWindow = new AMap.InfoWindow({
                            isCustom: true,  //使用自定义窗体
                            content: this.createInfoWindow(this.map,title, content.join("<br/>"),1),
                            offset: new AMap.Pixel(16, -5)
                        });

                        infoWindow.open(this.map, marker.getPosition());
                    }
                }
            }
        })
    }

    areaChange = (value, selectedOptions) => {
        console.log(value, selectedOptions,222)
        if(!value.length){
            this.setState({
                areaErorr:false
            })
        }
        let text="";
        //if(selectedOptions&&selectedOptions.length) selectedOptions.splice(0,1);
        selectedOptions.forEach(v=>{
            text+=v.Name;
        })
        this.props.form.setFieldsValue({
            RegionText:''
        })
        this.search(text)
    }

    searchArea = () => {
        const { form } = this.props; 
        let values=form.getFieldsValue();      
        if(!values.Region){           
            this.search(values.RegionText);
        }else{            
            this.search(values.RegionText, values.Region[2]);
        }; 
    }

    search = (text,citycode) => {
        let that=this;
        this.setState({
            searchLoading:true,
            hideSearchBox:false
        })
        console.log(citycode,text)
        AMap.service(["AMap.PlaceSearch"], function() {
            //构造地点查询类
            var placeSearch = new AMap.PlaceSearch({ 
                pageSize: 10, // 单页显示结果条数
                pageIndex: 1, // 页码
                city: `${citycode||''}`, // 兴趣点城市
                citylimit: true,  //是否强制限制在设置的城市内搜索
                map: that.map, // 展现结果的地图实例
                panel: "panel", // 结果列表将在此容器中进行展示。
                autoFitView: true // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围
            });
            //关键字查询
            placeSearch.search(text,function(status,result){
                if(status === 'complete' && result.info === 'OK') {
                    that.map.clearMap();
                    let list = result.poiList.pois;                   
                    for (var i = 0, marker; i < list.length; i++) {
                        var marker = new AMap.Marker({
                            position: [list[i].location.lng,list[i].location.lat],
                            icon: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b' + (i + 1) + '.png',
                            extData: {
                                id: i + 1
                            },
                            map: that.map
                        });                      
                        marker.on('click', function(){
                            let arr=result.poiList.pois.filter((item) => {
                                return item.location.lng===this.getPosition().lng&&item.location.lat===this.getPosition().lat;
                            });
                            //that.citycode=result.regeocode.addressComponent.adcode;
                            var title = `${arr[0].name}<br/><span>地址：</span>${arr[0].address}`,
                            content = [];                       
                            //content.push("<a >设为联系地址</a>");
                            var infoWindow = new AMap.InfoWindow({
                                isCustom: true,  //使用自定义窗体
                                content: that.createInfoWindow(that.map,title, content.join("<br/>"),2,arr),
                                offset: new AMap.Pixel(16, -5)
                            });

                            infoWindow.open(that.map, this.getPosition());
                            console.log(result,this.getPosition())                            
                        });                                
                    }
                    
                }                    
                console.log(status,result)
                that.setState({
                    searchLoading:false,                   
                },()=>{                  
                    let dom=document.querySelector('.amap_lib_placeSearch_ul');
                    if(dom){
                        dom.onclick=function(e){
                            let index=document.querySelector('.poibox.selected .poibox-icon').innerHTML-1;
                            let item=result.poiList.pois[index];
                            //实例化信息窗体
                            var title = `${item.name}<br /><span>地址：</span>${item.address}`,
                            content = [];                       
                        // content.push("<a >设为联系地址</a>");
                            var infoWindow = new AMap.InfoWindow({
                                isCustom: true,  //使用自定义窗体
                                content: that.createInfoWindow(that.map,title, content.join("<br/>"),2,[item]),
                                offset: new AMap.Pixel(16, -5)
                            });
    
                            infoWindow.open(that.map, item.location);                           
                        }
                    }
                })
            });
        });
    }

    

    onOk = () => {
        const { confirm ,form} = this.props;        
        form.validateFields((err,values)=>{
            console.log(values)
            if(err||!values.RegionText) return;
            let ProvId = values.Region[0];
            let CityId = values.Region[1];
            let DistrictId = values.Region[2];
            if(!DistrictId){
                this.setState({
                    areaErorr:true
                })
                return;
            }
            let type="marker";
            let overlays = this.map.getAllOverlays(type);
            let position = type == 'marker'? overlays[0].getPosition(): overlays[0].getPath()[0];
            let params={
                Prov:this.dataMap[ProvId].Name,
                ProvId:ProvId,
                City:this.dataMap[CityId].Name,
                CityId:CityId,
                District:this.dataMap[DistrictId].Name,
                DistrictId:DistrictId,
                Address:values.RegionText,
                Lng:position.lng,
                Lat:position.lat,
            }
            if(confirm && typeof confirm === 'function' ) confirm(params)
        })        
    }

    render(){
        const formItemLayout = {
            labelCol: {
              xs: { span: 4 },
              sm: { span: 4 },
              md: { span: 4 },
      
            },
            wrapperCol: {
              xs: { span: 20 },
              sm: { span: 20 },
              md: { span: 20 },
            },
        };
        const formItemLayout2 = {
            labelCol: {
              xs: { span: 4 },
              sm: { span: 4 },
              md: { span: 4 },
      
            },
            wrapperCol: {
              xs: { span: 20 },
              sm: { span: 20 },
              md: { span: 20 },
            },
        };
        const { form: { getFieldDecorator,getFieldValue } ,children} = this.props;
        const { visible,searchLoading,hideSearchBox ,areaErorr} = this.state;
       // console.log('hideSearchBox',hideSearchBox)
       const errorobj=areaErorr?{validateStatus:'error',style:{marginBottom:0}}:{};
        return(
            <Modal
              title={'修改取货地址'}
              width={850}
              visible={visible}
              onCancel={this.hideModal}
              onOk={this.onOk}
              centered
            >
                <Form>
                    {this.props.top}  
                    <FormItem
                        //{...formItemLayout}
                        labelCol={{span:4}}
                        wrapperCol={{span:14}}
                        label="取货地址"
                        {...errorobj}                       
                        extra={
                            areaErorr?<span className="xkd-color-error">请选择完整省市区（县、镇、街道）的取货地址</span>:''
                        }
                    >
                        {getFieldDecorator('Region', {                 
                        rules: [{ required: true, message: '请选择取货地址' }],
                        })(
                            <Cascader options={regionDatas} placeholder="" onChange={this.areaChange} changeOnSelect expandTrigger="hover"/>
                        )}

                    </FormItem>
                    <Row>
                        <Col offset={4} span={20}>
                            <FormItem
                               // {...formItemLayout}
                               style={{ marginBottom: 0 }}
                            >
                                <Row>
                                    <Col span={20}>
                                        <FormItem>
                                            {
                                                getFieldDecorator('RegionText')(
                                                    <Input  placeholder=""/>
                                                )
                                            }                                            
                                        </FormItem>
                                    </Col> 
                                    <Col span={4} className="xkd-text-right">
                                        <FormItem>
                                            <Button onClick={this.searchArea} loading={searchLoading}>搜索地图</Button>
                                        </FormItem>
                                    </Col>   
                                </Row>                       
                            </FormItem>
                        </Col>
                    </Row> 
                    <FormItem
                        {...formItemLayout2}
                        label="地图定位"
                        help={
                            <Fragment>
                                <div className="xkd-mt8">注：取货地址修改后，将影响您以下两点： </div>
                                <div>1.已设置的配送范围信息将被清空：请修改地址后记得重新配置配送范围</div>
                                <div>2.已开通的第三方配送都会重新审核，请准备3～7天审核期的其他配送方式；</div>
                            </Fragment>
                        }
                    >
                        {/* {getFieldDecorator('Name', {                 
                        rules: [{ required: true, message: '请选择至少一种支付方式!' }],
                        })(
                            <div className={`${styles.mapContainer}`}>
                                <div id="distributionModalMapContainer" style={{width:480,height:288}}></div>
                            </div>
                        )}                         */}
                        <div className={`${styles.mapContainer} xkd-position-relative ${hideSearchBox?'':styles.pullright}`} style={{overflow:'hidden'}}>
                            <div id="distributionModalMapContainer" style={{height:400}}></div>
                            <div style={{position:"absolute",top:0,left:0,zIndex:200,width:200,height:400,overflow:'hidden'}} className={`${hideSearchBox?styles.hideSearchBox:''}`}>
                                <div id="panel" style={{width:217,height:400,overflowY:'scroll',overflowX:'hidden'}}></div>
                            </div>                            
                        </div>
                    </FormItem> 
                    {this.props.bottom}                  
                </Form>
            </Modal>
        )
    }
}